package com.education.ai.service.impl;

import com.education.ai.service.WanxiangService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 通义万象服务实现类
 * 使用wanx2.1-t2i-turbo模型生成图片，wanx2.1-t2v-turbo模型生成视频
 */
@Slf4j
@Service
public class WanxiangServiceImpl implements WanxiangService {

    @Value("${tongyi.wanxiang.api.key}")
    private String apiKey;

    @Value("${tongyi.wanxiang.api.uri}")
    private String apiBaseUri;

    @Value("${tongyi.wanxiang.api.image-model}")
    private String imageModel;

    @Value("${tongyi.wanxiang.api.video-model}")
    private String videoModel;

    @Value("${tongyi.wanxiang.api.video-endpoint}")
    private String videoEndpoint;

    @Autowired
    private RestTemplate restTemplate;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String generateImage(String prompt) {
        try {
            log.info("调用通义万象API生成图片，模型: {}, 提示词: {}", imageModel, prompt);
            
            String apiUri = apiBaseUri + "/" + imageModel;
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> input = new HashMap<>();
            Map<String, Object> parameters = new HashMap<>();
            
            input.put("prompt", prompt);
            
            parameters.put("style", "photographic");
            parameters.put("size", "1024*1024");
            parameters.put("n", 1);
            
            requestBody.put("model", "wanx2.1-t2i-turbo");
            requestBody.put("input", input);
            requestBody.put("parameters", parameters);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);
            ResponseEntity<String> response = restTemplate.postForEntity(apiUri, request, String.class);

            JsonNode responseJson = objectMapper.readTree(response.getBody());
            String imageUrl = responseJson.path("output").path("url").asText();
            
            log.info("成功从通义万象获取图片URL: {}", imageUrl);
            return imageUrl;
        } catch (Exception e) {
            log.error("通义万象图片生成API调用失败", e);
            throw new RuntimeException("图片生成失败: " + e.getMessage(), e);
        }
    }

    @Override
    public String generateVideo(String prompt, int durationSeconds) {
        try {
            log.info("调用通义万象API生成视频，模型: {}, 提示词: {}, 时长: {}秒", videoModel, prompt, durationSeconds);
            
            // 构建完整的API URL
            String apiUri = apiBaseUri + "/aigc/video-generation/video-synthesis";
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            headers.set("X-DashScope-Async", "enable"); // 启用异步调用
            
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", videoModel);
            
            Map<String, Object> input = new HashMap<>();
            input.put("prompt", prompt);
            requestBody.put("input", input);
            
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("size", "1280*720");
            parameters.put("duration", durationSeconds);
            requestBody.put("parameters", parameters);
            
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
            
            log.info("发送请求到通义万象API: {}", apiUri);
            log.debug("请求体: {}", objectMapper.writeValueAsString(requestBody));
            
            ResponseEntity<Map> response = restTemplate.exchange(
                apiUri,
                HttpMethod.POST,
                requestEntity,
                Map.class
            );
            
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();
                log.info("通义万象API响应: {}", responseBody);
                
                if (responseBody.containsKey("output") && responseBody.get("output") instanceof Map) {
                    Map<String, Object> output = (Map<String, Object>) responseBody.get("output");
                    if (output.containsKey("task_id")) {
                        return (String) output.get("task_id");
                    }
                }
                throw new RuntimeException("API响应格式不正确: " + responseBody);
            } else {
                throw new RuntimeException("通义万象API调用失败: " + response.getBody());
            }
        } catch (Exception e) {
            log.error("调用通义万象API生成视频失败", e);
            throw new RuntimeException("生成视频失败: " + e.getMessage());
        }
    }

    @Override
    public String generateLessonImage(String subject, String topic, String content) {
        String prompt = String.format(
                "请生成一张适合%s学科《%s》主题的教学插图。内容与以下教学点相关：%s",
                subject, topic, content);
        return generateImage(prompt);
    }
} 